package cn.zmit.kuxi.activity;

import java.util.HashMap;
import java.util.Map;
import java.util.Timer;
import java.util.TimerTask;

import com.lidroid.xutils.ViewUtils;
import com.lidroid.xutils.view.annotation.ViewInject;
import com.lidroid.xutils.view.annotation.event.OnClick;
import com.xdroid.common.utils.PreferenceHelper;
import com.xdroid.common.utils.ScreenUtils;
import com.xdroid.common.utils.StringUtils;
import com.xdroid.common.utils.ToastUtils;
import com.xdroid.functions.request.JsonData;
import com.xdroid.request.extension.XDroidRequest;
import com.xdroid.request.extension.config.DataType;
import com.xdroid.request.extension.impl.OnRequestListenerAdapter;
import android.annotation.SuppressLint;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.os.Build.VERSION;
import android.view.Gravity;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.EditText;
import android.widget.RelativeLayout;
import android.widget.TextView;
import cn.zmit.kuxi.R;
import cn.zmit.kuxi.contants.Constants;
import cn.zmit.kuxi.contants.Response;
import cn.zmit.kuxi.contants.SPConstants;
import cn.zmit.kuxi.request.RequestTask;

/** * @author @parameter * @return */
public class SetNumActivity extends BaseActivity {
	@ViewInject(R.id.et_new_num)
	private EditText et_new_num;
	@ViewInject(R.id.ed_new_code)
	private EditText ed_new_code;
	@ViewInject(R.id.tv_new_get_code)
	private TextView tv_new_get_code;
	String phone, code, userId;
	@SuppressLint("HandlerLeak")
	private Handler handler = new Handler() {
		public void handleMessage(android.os.Message msg) {
			switch (msg.what) {
			case Constants.EXECUTE_LOADING:
				tv_new_get_code.setText(msg.arg1 + "秒后重新获取");
				if (msg.arg1 == 0) {
					closeTimer();
					tv_new_get_code.setTextColor(getResources().getColor(
							R.color.white));
					tv_new_get_code.setClickable(true);
				}
				break;
			case Constants.EXECUTE_FINISH:
				tv_new_get_code.setText("重新获取验证码");
				tv_new_get_code.setTextColor(getResources().getColor(
						R.color.white));

				break;

			}
			super.handleMessage(msg);
		};
	};

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_set_num);
		ViewUtils.inject(this);
		userId = PreferenceHelper.readString(context,
				SPConstants.SHARED_PREFERENCE_NAME, SPConstants.USERID, "");
		phone = et_new_num.getText().toString().trim();
		code = ed_new_code.getText().toString().trim();
		initTitleBar();

	}

	private class onRequestListener extends OnRequestListenerAdapter<Object> {
		@Override
		public void onDone(XDroidRequest<?> request, String response,
				DataType dataType) {
			// TODO Auto-generated method stub
			super.onDone(request, response, dataType);
			dismissProgressDialog();
			JsonData jsonData = JsonData.create(response);
			if (jsonData.optString("code").equals("0")) {
				ToastUtils.show(context, jsonData.optString(Response.MASSAGE));
			} else {
				ToastUtils.show(context, "请求错误");
			}
		}

		@Override
		public void onRequestPrepare() {
			// TODO Auto-generated method stub
			super.onRequestPrepare();
			showProgressDialog("正在获取验证码……");
		}

		@Override
		public void onRequestFailed(String error) {
			// TODO Auto-generated method stub
			super.onRequestFailed(error);
			dismissProgressDialog();
		}
	}

	@OnClick({ R.id.tv_new_get_code })
	private void OnClick(View v) {
		switch (v.getId()) {
		case R.id.tv_new_get_code:
			// phone=et_new_num.getText().toString().trim();
			if (checkFormPhone()) {
				getData();
				tv_new_get_code.setTextColor(getResources().getColor(
						R.color.white));
				tv_new_get_code.setClickable(false);
				startTimer();
			}

			break;

		default:
			break;
		}
	}

	private void getData() {
		String type = "1";
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("phone", phone);
		map.put("type", type);
		RequestTask.getInstance().doReSetPhone(this, map,
				new onRequestListener());
	}

	private void initTitleBar() {
		setTitleView("号码设置");

		final TextView editTextView = new TextView(context);
		RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(
				(int) ScreenUtils.dpToPx(context, 40),
				RelativeLayout.LayoutParams.MATCH_PARENT);
		editTextView.setLayoutParams(params);
		editTextView.setGravity(Gravity.CENTER);
		editTextView.setTextColor(getResources().getColor(R.color.black));
		editTextView.setTextSize(14);
		editTextView.setText("完成");
		com.xdroid.common.utils.ViewUtils.setPadding(editTextView, 0, 0, 20, 0);
		editTextView.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				if (checkForm()) {
					commit();

				}

			}
		});
		getTitleBar().addRightView(editTextView);
	}

	private void commit() {
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("phone", phone);
		map.put("salt", code);
		map.put("user_id", userId);
		RequestTask.getInstance().doCommit(this, map,
				new CommitOnRequestListener());
	}

	private class CommitOnRequestListener extends
			OnRequestListenerAdapter<Object> {
		@Override
		public void onDone(XDroidRequest<?> request, String response,
				DataType dataType) {
			// TODO Auto-generated method stub
			super.onDone(request, response, dataType);
			dismissProgressDialog();
			JsonData jsonData = JsonData.create(response);

			if (jsonData.optString("code").equals("0")) {
				// ToastUtils.show(context, jsonData.optString("message"));
				Intent intent = new Intent();
				intent.putExtra("phone", phone);
				PreferenceHelper.write(context, "phone", SPConstants.PHONE,
						phone);
				setResult(1, intent);
				finish();
			} else {
				ToastUtils.show(context, "提交失败，请重试");
			}
		}

		@Override
		public void onRequestPrepare() {
			// TODO Auto-generated method stub
			super.onRequestPrepare();
			showProgressDialog("正在提交……");
		}

		@Override
		public void onRequestFailed(String error) {
			// TODO Auto-generated method stub
			super.onRequestFailed(error);
			dismissProgressDialog();
		}
	}

	private Boolean checkForm() {
		phone = et_new_num.getText().toString().trim();
		code = ed_new_code.getText().toString().trim();
		if (StringUtils.isEmpty(phone)) {
			ToastUtils.show(context, "手机号不能为空");
			return false;
		} else if (!StringUtils.isPhone(phone)) {
			ToastUtils.show(context, "请输入合法的手机号");
			return false;
		} else if (StringUtils.isEmpty(code)) {
			ToastUtils.show(context, "请输入验证码");
		}
		return true;
	}

	private Boolean checkFormPhone() {
		phone = et_new_num.getText().toString().trim();

		if (StringUtils.isEmpty(phone)) {
			ToastUtils.show(context, "手机号不能为空");
			return false;
		} else if (!StringUtils.isPhone(phone)) {
			ToastUtils.show(context, "请输入合法的手机号");
			return false;
		}

		return true;
	}

	// 开启倒计时
	private int mTimerId = 60;

	private TimerTask timerTask;

	private Timer timer;

	public void startTimer() {
		if (timerTask == null) {
			timerTask = new TimerTask() {

				@Override
				public void run() {
					Message msg = new Message();
					msg.what = Constants.EXECUTE_LOADING;
					msg.arg1 = (int) (--mTimerId);
					handler.sendMessage(msg);
				}
			};
			timer = new Timer();
			timer.schedule(timerTask, 100, 1000);
		}
	}

	// 结束计时
	private void closeTimer() {
		if (timer != null) {
			timer.cancel();
			timer = null;
		}
		if (timerTask != null) {
			timerTask = null;
		}
		mTimerId = 60;
		handler.sendEmptyMessage(Constants.EXECUTE_FINISH);
	}

}
